package com.qipay.sp.excutor.bawang;

import com.alibaba.fastjson.JSONObject;
import com.qipay.baas.model.Order;
import com.qipay.order.config.OrderStateEnum;
import com.qipay.order.service.OrderService;
import com.qipay.scalar.type.ApiStatusEnum;
import com.qipay.scalar.type.ApiTypeEnum;
import com.qipay.sp.excutor.AbstractExcutor;
import com.qipay.utils.DateUtils;
import com.qipay.utils.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class BawangAliNativeExcutor extends AbstractExcutor {

    private final static String API_URL="api_url";
    @Autowired
    OrderService orderService;

    @Override
    protected Map<String, Object> getApiParams(Order order, Map<String, Object> spconfig, Map<String, Object> extendOrderParams) {
        Map<String, Object> apiParams = new HashMap<>();
        apiParams.put("pay_orderid",order.getTradeNo());
        apiParams.put("pay_applydate", DateUtils.sdf.format(new Date()));
        apiParams.put("pay_amount",
                new BigDecimal(order.getAmount()).divide(new BigDecimal("100")));
        apiParams.put("pay_productname",order.getBody());

        return apiParams;
    }

    @Override
    protected Map<String, Object> run(Map<String, Object> spconfig, Map<String, Object> params) throws Exception {
        Object apiUrl = getVal(spconfig, API_URL);
        Object pay_memberid = getVal(spconfig, "pay_memberid");//商户uid
        Object notify_url= getVal(spconfig, "notify_url");
        Object return_url= getVal(spconfig, "return_url");

        Object key= getVal(spconfig, "key");

        params.put("pay_memberid",pay_memberid);
        params.put("pay_notifyurl",notify_url);
        params.put("pay_callbackurl",return_url);
        String pay_productname = params.remove("pay_productname").toString();

        String pay_md5sign = MD5Util.getSign(params,key.toString()).toUpperCase();
        params.put("pay_md5sign",pay_md5sign);
        params.put("pay_productname",pay_productname);
        params.put("device-type","1");


        String result = generateAutoSubmitHtml(params,apiUrl.toString());
        logger.info(getClass().getName() + "返回结果：" + result);
        if (StringUtils.isBlank(result)) {
            throw new Exception("请求bawang支付接口失败");
        }

        Order order = orderService.getByTradeNo(params.get("pay_orderid").toString());
        Map<String, Object> resultMap = new HashMap<>();

        resultMap.put("status", ApiStatusEnum.OK.getCode());
        resultMap.put("pay_info",result);
        order.setState(OrderStateEnum.WAITING.getType());

        orderService.update(order);
        return resultMap;
    }
}
